package com.haisen.controller;


import com.alibaba.fastjson.JSON;
import com.haisen.core.annotation.SystemLog;
import com.haisen.core.utils.PageResultSet;
import com.haisen.core.utils.Result;
import com.haisen.dataobject.dto.UserDto;
import com.haisen.dataobject.dto.VerifyPubSubDTO;
import com.haisen.dataobject.entity.User;
import com.haisen.dataobject.entity.VerifyPubSub;
import com.haisen.dataobject.query.VerifyPubSubQuery;
import com.haisen.service.JobNoService;
import com.haisen.service.UserService;
import com.haisen.service.VerifyPubSubService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@Controller
@RequestMapping("/verifypubsub")
@Slf4j
public class VerifyPubSubController {

    @Autowired
    private VerifyPubSubService verifyPubSubService;

    @Autowired
    private UserService userService;

    @Autowired
    private JobNoService jobNoService;

    @RequiresPermissions("verifypubsub:view")
    @GetMapping
    public String page(Model model){
        setCommondDate(model);
        return "produce/verifypubsub";
    }


    @ResponseBody
    @RequestMapping("/list")
    @RequiresPermissions("verifypubsub:view")
    public PageResultSet<VerifyPubSubDTO> findBypage(VerifyPubSubQuery verifyPubSubQuery){
        return verifyPubSubService.findByPage(verifyPubSubQuery);
    }

    @ResponseBody
    @RequiresPermissions("verifypubsub:create")
    @PostMapping("/create")
    @SystemLog("订阅验证码")
    public Result create(@Validated VerifyPubSub verifyPubSub) {
        verifyPubSubService.create(verifyPubSub);
        return Result.success();
    }


    @ResponseBody
    @PostMapping("/update")
    @RequiresPermissions("verifypubsub:update")
    public Result update(@Validated VerifyPubSub verifyPubSub) {
        log.info("修改:{}", JSON.toJSONString(verifyPubSub));
        verifyPubSubService.update(verifyPubSub);
        return Result.success();
    }

    @ResponseBody
    @RequiresPermissions("verifypubsub:delete")
    @PostMapping("/delete")
    public Result delete(@RequestParam("id") Long[] ids) {
        verifyPubSubService.delete(ids);
        return Result.success();
    }



    private void setCommondDate(Model model) {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        User user = userService.findByUsername(username);
        //user对象传递，更多信息传递出去了，改用json来传递有限信息
        //model.addAttribute("user",user);
        User userTrans = new User();
        userTrans.setUsername(username);
        userTrans.setNickName(user.getNickName());
        model.addAttribute("user",userTrans);
        model.addAttribute("jobNoList", jobNoService.list2Tree());
    }

}
